package com.caow.baselibrary.http

import com.caow.baselibrary.GlobalConfig
import com.caow.baselibrary.http.interceptor.HeaderInterceptor
import com.caow.baselibrary.http.interceptor.Level
//import com.caow.baselibrary.http.interceptor.LoggingInterceptor
import com.caow.baselibrary.http.interceptor.TokenInterceptor
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import okhttp3.ConnectionPool
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.internal.platform.Platform
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.net.Proxy
import java.util.concurrent.TimeUnit

/**
 * @Author caow
 * 2022/11/24
 */
object BaseHttpManager {

    private val mInterceptorList = ArrayList<Interceptor>()

    private val headerMap = HashMap<String, String>()

    private val retrofit: Retrofit by lazy {
        val gson = GsonBuilder()
            .setLenient()
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .create()
        Retrofit.Builder()
            .client(getOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl(GlobalConfig.baseUrl)
            .build()
    }

    fun addInterceptor(interceptor: Interceptor) {
        mInterceptorList.add(interceptor)
    }

    fun addHeader(key: String, value: String) {
        headerMap[key] = value
    }

    fun removeHeader(key: String) {
        headerMap.remove(key)
    }

    private fun getOkHttpClient(): OkHttpClient {
        val builder = OkHttpClient.Builder()
            .connectTimeout(20L, TimeUnit.SECONDS)
            .addInterceptor(HeaderInterceptor(headerMap))
            .addInterceptor(TokenInterceptor())
//            .addNetworkInterceptor(LoggingInterceptor().apply {
//                isDebug = GlobalConfig.DEBUG
//                level = Level.BASIC
//                type = Platform.INFO
//                requestTag = "Request"
//                requestTag = "Response"
//            })
            .writeTimeout(20L, TimeUnit.SECONDS)
            .proxy(if (GlobalConfig.DEBUG) null else Proxy.NO_PROXY)
            .connectionPool(ConnectionPool(8, 15, TimeUnit.SECONDS))

        for (interceptor in mInterceptorList) {
            builder.addInterceptor(interceptor)
        }

        return builder.build()
    }

    fun <T> create(service: Class<T>?): T =
        retrofit.create(service!!) ?: throw RuntimeException("Api service is null!")

}